<template>
  <bs-dialog
    v-model="visible"
    :title="title"
    :width="500"
    confirmBtnText="上传"
    cancelBtnText="关闭"
    :confirmBtnFn="handleUpload"
  >
    <div class="import-content">
      <!--下载模版-->
      <div class="model-wrap">
        <el-button link type="primary" @click="downloadTemplate">下载导入模版</el-button>
      </div>
      <!--上传导入-->
      <div class="upload-wrap">
        <el-upload
          :disabled="isUpload"
          ref="uploadRef"
          :auto-upload="false"
          :on-change="handleFileChange"
          :show-file-list="false"
          :limit="1"
          accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
        >
          <template #trigger>
            <el-button type="primary" :disabled="isUpload">选择文件</el-button>
          </template>
          <span class="file-name" v-if="file">{{file.name}}</span>
          <!--上传进度条-->
          <div class="progress-wrap" v-if="isUpload">
            <el-progress :percentage="percent" />
          </div>
        </el-upload>
      </div>
    </div>
  </bs-dialog>
</template>
<script lang="ts" setup>
import {ref} from 'vue'
import * as API from '@/service/modules/resource'
import {UploadFile, ElMessage} from 'element-plus'

const visible = ref(false)
const title = '设备批量导入'
const uploadRef = ref()
const file = ref<UploadFile>()
const percent = ref(0)
const isUpload = ref(false)

const open = () => {
  visible.value = true
  file.value = undefined
}

/**
 * 下载导入模版
 */
const downloadTemplate = () => {
  API.importDataTemplate()
}

const handleFileChange = (uploadFile: UploadFile) => {
  console.log(uploadFile)
  file.value = uploadFile
  uploadRef.value.clearFiles()
}


const handleUpload = async () => {
  // uploadRef.value.submit()
  try {
    const formData = new FormData()
    const f = file.value?.raw as File
    formData.append('file', f)
    isUpload.value = true
    const res:any = await API.importData(formData, {
      onUploadProgress (e) {
        percent.value = parseInt(String((e.progress || 0) * 100))
      }
    })
    ElMessage.success(res.msg || '上传成功')
    visible.value = false
    isUpload.value = false
    return true
  } catch (e) {
    isUpload.value = false
    return Promise.reject()
  }
}

defineExpose({
  open
})
</script>
<style lang="scss" scoped>
.import-content {
  padding: 16px;
}
.upload-wrap  {
  margin-top: 16px;
}
.file-name {
  margin-left: 8px;
  color: var(--gray-color)
}
</style>